<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Artisan;


use App\Admin\Filters\WorshipPptFilter;
use App\Admin\Models\WorshipPpt;
use App\Admin\Requests\WorshipPptRequest;
use App\Admin\Resources\WorshipPptResource;
use App\Admin\Models\WorshipHymn;
use App\Admin\Models\WorshipBibleChapter;
use App\Admin\Models\WorshipBibleVolume;
use App\Admin\Models\SystemMedia;
use App\Admin\Models\SystemMediaCategory;
use App\Admin\Models\Config;
use App\Admin\Models\SystemModel;
use Cristal\Presentation\PPTX;
use Illuminate\Http\Request;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\DB;

class TestJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $func;

    public $configs;

    public $data;

    // 每张经文页显示的章节数量
    public $lectionNumbers = 7;

    // 存储导出PPTX的分类名称
    public $pptxCate = '主日PPT';

    // 存储导出PPTX的目录
    public $pptxPath = 'public/uploads/';

    // 存储PPTX模版的目录
    public $pptxTemplatePath = 'public/pptx/template/';

    // 存储PPTX资源的目录
    public $pptxResourcePath = 'public/pptx/resource/';

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($func, $data)
    {
        $this->func = $func;
        $this->data = $data;
        $this->configs = array_column(Config::getByCategorySlug('ppt_export')->toArray(), 'value', 'slug');
        foreach ($this->configs as $key => $value) {
            $this->configs[$key] = 'public'.$value;
        }
    }

    public function hymn(){
        // hymn
        $worshipHymnInfo = $this->data['worshipHymnInfo'];
        $worshipHymnPPTX = new PPTX($this->configs['hymn']);
        $worshipHymnPPTX->template(function ($matches) use ($worshipHymnInfo) {
            return $worshipHymnInfo[$matches['needle']] ?? null;
        });
        $worshipHymnPPTX->saveAs($this->pptxResourcePath.'hymn.pptx');

        // hymn_*
        for ($i=1; $i <= $worshipHymnInfo['page']; $i++) { 
            $songPPTX = new PPTX($this->configs['hymn_song']);
            $worshipHymnInfo['content'] = explode("\n", $worshipHymnInfo['content_'.$i]);
            $content = [];
            foreach ($worshipHymnInfo['content'] as $key => $value) {
                $content['word'.$key] = $value;
            }
            // 第一页渲染歌名
            if ($i==1) {
                $content['name'] = $worshipHymnInfo['name'];
            }
            $songPPTX->template(function ($matches) use ($content) {
                return $content[$matches['needle']] ?? null;
            });
            $songPPTX->saveAs($this->pptxResourcePath."/hymn_{$i}.pptx");
        }
    }

    public function response_bible(){
        // response_bible
        $worshipPptInfo = $this->data['worshipPptInfo'];
        $responseBiblePPTX = new PPTX($this->configs['response_bible']);
        $responseBiblePPTX->template(function ($responseBibleMatches) use ($worshipPptInfo) {
            return $worshipPptInfo[$responseBibleMatches['needle']] ?? null;
        });
        
        $responseBiblePPTX->saveAs($this->pptxResourcePath.'response_bible.pptx');

        // response_bible_*
        $responseBibleList = $this->data['responseBibleList'];
        $responseBibleCount = count($responseBibleList);
        $responseBiblePageInfo = getPage(1, $responseBibleCount, $this->lectionNumbers);
        for ($i=1; $i <= $responseBiblePageInfo['totalPages']; $i++) { 
            $cPageInfo = getPage($i, $responseBibleCount, $this->lectionNumbers);
            $cList = array_slice($responseBibleList, $cPageInfo['firstRow'], $cPageInfo['listRows']);
            $lectionPPTX = new PPTX($this->configs['lection']);
            $lectionPPTX->template(function ($matches) use ($cList) {
                $temp = [];
                foreach ($cList as $key => $value) {
                    $temp['vcv'.$key] = $value['vcv'];
                    $temp['lection'.$key] = $value['lection'];
                }
                return $temp[$matches['needle']] ?? null;
            });
            $lectionPPTX->saveAs($this->pptxResourcePath."/response_bible_{$i}.pptx");
        }
    }

    public function praise(){
        // praise_*
        $praiseInfo = $this->data['praiseInfo'];
        $praiseList = [];
        foreach ($praiseInfo as $key => $value) {
            foreach ($value as $key2 => $value2) {
                $content = [];
                if (strstr($key2, 'content_') && $value2) {
                    if ($key2=='content_1') {
                        $content['name'] = $value['name'];
                    }
                    $value2 = explode("\n", $value2);
                    foreach ($value2 as $key3 => $value3) {
                        $content['word'.$key3] = $value3;
                    }
                    array_push($praiseList, $content);
                }
            }
        }
        $praisePage = count($praiseList);
        for ($i=0; $i < $praisePage; $i++) { 
            $songPPTX = new PPTX($this->configs['praise_song']);
            $content = $praiseList[$i];
            $songPPTX->template(function ($matches) use ($content) {
                return $content[$matches['needle']] ?? null;
            });
            $j = $i+1;
            $songPPTX->saveAs($this->pptxResourcePath."/praise_{$j}.pptx");
        }
    }

    public function choir(){
        // choir
        $choirInfo = $this->data['choirInfo'];
        $choirPPTX = new PPTX($this->configs['choir']);
        $choirPPTX->template(function ($matches) use ($choirInfo) {
            return $choirInfo[$matches['needle']] ?? null;
        });
        $choirPPTX->saveAs($this->pptxResourcePath.'choir.pptx');

        // choir_*
        for ($i=1; $i <= $choirInfo['page']; $i++) { 
            $songPPTX = new PPTX($this->configs['choir_song']);
            $choirInfo['content'] = explode("\n", $choirInfo['content_'.$i]);
            $content = [];
            foreach ($choirInfo['content'] as $key => $value) {
                $content['word'.$key] = $value;
            }
            // 第一页渲染歌名
            if ($i==1) {
                $content['name'] = $choirInfo['name'];
            }
            $songPPTX->template(function ($matches) use ($content) {
                return $content[$matches['needle']] ?? null;
            });
            $songPPTX->saveAs($this->pptxResourcePath."/choir_{$i}.pptx");
        }
    }

    public function preach(){
        $worshipPptInfo = $this->data['worshipPptInfo'];
        // preach
        $preachPPTX = new PPTX($this->configs['preach']);
        $preachPPTX->template(function ($matches) use ($worshipPptInfo) {
            return $worshipPptInfo[$matches['needle']] ?? null;
        });
        $preachPPTX->saveAs($this->pptxResourcePath.'preach.pptx');
        
        // preach_*
        $preachLectionList = $this->data['preachLectionList']; 
        $preachLectionCount = count($preachLectionList);
        $preachLectionPageInfo = getPage(1, $preachLectionCount, $this->lectionNumbers);
        for ($i=1; $i <= $preachLectionPageInfo['totalPages']; $i++) { 
            $cPageInfo = getPage($i, $preachLectionCount, $this->lectionNumbers);
            $cList = array_slice($preachLectionList, $cPageInfo['firstRow'], $cPageInfo['listRows']);
            $preachLectionInfo['vc'] = $worshipPptInfo['preach_lection'];
            $preachLectionInfo['lection'] = implode(array_column($cList, 'lection'));
            $lectionPPTX = new PPTX($this->configs['preach_lection']);
            $lectionPPTX->template(function ($matches) use ($preachLectionInfo) {
                return $preachLectionInfo[$matches['needle']] ?? null;
            });
            $lectionPPTX->saveAs($this->pptxResourcePath."/preach_{$i}.pptx");
        }
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $this->{$this->func}();
        // exit;
        // info('start'.$this->id);
        // $command = "admin:make-worship-ppt".$this->id;
        // Artisan::call($command);
        // info('end'.$this->id);

        // $worshipPpt = app(WorshipPpt::class);
        // $worshipBibleVolume = app(WorshipBibleVolume::class);
        // $worshipPptInfo = $worshipPpt->find(2)->toArray();        

        // $responseBibleList = $worshipBibleVolume->lections($worshipPptInfo['response_bible']);
        // $responseBibleCount = count($responseBibleList);
        // $responseBiblePageInfo = getPage(1, $responseBibleCount, $this->lectionNumbers);


        // $preachLectionList = $worshipBibleVolume->lections($worshipPptInfo['preach_lection']);
        // $preachLectionCount = count($preachLectionList);
        // $preachLectionPageInfo = getPage(1, $preachLectionCount, $this->lectionNumbers);


        // $praisePage = 12;
        // // 合并PPTX
        // $headPPTX = new PPTX($this->configs['head']);

        // $headPPTXName = $this->pptxResourcePath.'hymn.pptx';
        // if (file_exists($headPPTXName)) {
        //     $worshipHymnPPTX = new PPTX($headPPTXName);
        //     $headPPTX->addSlides($worshipHymnPPTX->getSlides());
        //     for ($i=1; $i <= $worshipHymnInfo['page']; $i++) { 
        //         $pptx = new PPTX($this->pptxResourcePath."/hymn_{$i}.pptx");
        //         $headPPTX->addSlides($pptx->getSlides());
        //     }
        // }
        
        // $responseBiblePPTXName = $this->pptxResourcePath.'response_bible.pptx';
        // if (file_exists($responseBiblePPTXName)) {
        //     $responseBiblePPTX = new PPTX($responseBiblePPTXName);
        //     $headPPTX->addSlides($responseBiblePPTX->getSlides());
        //     for ($i=1; $i <= $responseBiblePageInfo['totalPages']; $i++) { 
        //         $pptx = new PPTX($this->pptxResourcePath."/response_bible_{$i}.pptx");
        //         $headPPTX->addSlides($pptx->getSlides());
        //     } 
        // }
        
        // $praisePPTXName = $this->configs['praise'];
        // if (file_exists($praisePPTXName)) {
        //     $praisePPTX = new PPTX($praisePPTXName);
        //     $headPPTX->addSlides($praisePPTX->getSlides());
        //     for ($i=1; $i <= $praisePage; $i++) { 
        //         $pptx = new PPTX($this->pptxResourcePath."/praise_{$i}.pptx");
        //         $headPPTX->addSlides($pptx->getSlides());
        //     }  
        // }
        
        // $choirPPTXName = $this->pptxResourcePath.'choir.pptx';
        // if (file_exists($choirPPTXName)) {
        //     $choirPPTX = new PPTX($choirPPTXName);
        //     $headPPTX->addSlides($choirPPTX->getSlides());
        //     for ($i=1; $i <= $choirInfo['page']; $i++) { 
        //         $pptx = new PPTX($this->pptxResourcePath."/choir_{$i}.pptx");
        //         $headPPTX->addSlides($pptx->getSlides());
        //     }    
        // }

        // $preachPPTXName = $this->pptxResourcePath.'preach.pptx';
        // if (file_exists($preachPPTXName)) {
        //     $preachPPTX = new PPTX($preachPPTXName);
        //     $headPPTX->addSlides($preachPPTX->getSlides());
        //     for ($i=1; $i <= $preachLectionPageInfo['totalPages']; $i++) { 
        //         $pptx = new PPTX($this->pptxResourcePath."/preach_{$i}.pptx");
        //         $headPPTX->addSlides($pptx->getSlides());
        //     }     
        // }
        
        // $eucharistPPTXName = $this->configs['eucharist'];
        // if (file_exists($eucharistPPTXName)) {
        //     $eucharistPPTX = new PPTX($eucharistPPTXName);
        //     $headPPTX->addSlides($eucharistPPTX->getSlides());
        // }

        // $prayerPPTXName = $this->configs['prayer'];
        // if (file_exists($prayerPPTXName)) {
        //     $prayerPPTX = new PPTX($prayerPPTXName);
        //     $headPPTX->addSlides($prayerPPTX->getSlides());
        // }
        
        // $newFriendPPTXName = $this->configs['new_friend'];
        // if (file_exists($newFriendPPTXName)) {
        //     $newFriendPPTX = new PPTX($newFriendPPTXName);
        //     $headPPTX->addSlides($newFriendPPTX->getSlides());
        // }

        // $familyReportPPTXName = $this->configs['family_report'];
        // if (file_exists($familyReportPPTXName)) {
        //     $familyReportPPTX = new PPTX($familyReportPPTXName);
        //     $headPPTX->addSlides($familyReportPPTX->getSlides());
        // }
        
        // $tailPPTXName = $this->configs['tail'];
        // if (file_exists($tailPPTXName)) {
        //     $tailPPTX = new PPTX($tailPPTXName);
        //     $headPPTX->addSlides($tailPPTX->getSlides());
        // }
    
        // // PPTX文件名称
        // $pptxName = 'worship '.$worshipPptInfo['worship_date'].'.pptx';
        // $path = $this->pptxPath.$pptxName;
        // $headPPTX->saveAs($path);
        // $pptxUrl = config()->get('app.url').'/'.$path;
        // // 存储到数据库
        // DB::beginTransaction();
        // // 更新或创建文件分类
        // $cateData['name'] = $this->pptxCate;;
        // $cateData['parent_id'] = 0;
        // $cate = SystemMediaCategory::updateOrCreate($cateData);
        // // 获取文件信息
        // $file = UploadedFile::fake()->image($path);
        // // 存储文件信息
        // $mediaData['filename'] = $pptxName;
        // $mediaData['ext'] = 'pptx';
        // $mediaData['category_id'] = $cate->id;
        // $mediaData['path'] = '/'.$path;
        // $mediaData['path_key'] = md5($path);
        // $mediaData['size'] = $file->getSize();
        // $mediaData['mime_type'] = $file->getMimeType();
        // $media = SystemMedia::create($mediaData);
        // if ($cate && $media) {
        //     DB::commit();
        // } else {
        //     DB::rollBack();
        // }
    }
}
